let wifiConfigTimer = null;
let wifiConnectTimer = null;

class WeChat_EConnectWifi {
  constructor(params) {
    this.params = params;
    this.hasOnconnectedWifi = false;
    // const { accessToken, deviceSerial, validateCode, customId } = params;
  }

  // 扫描二维码
  scanDevice(accessToken) {
    wx.scanCode({
      success(res) {
        console.log("扫描结果", res);
        const result = res.result;
        console.log(result);
        const temp = result.split("\r");
        console.log("temp", temp);
        if (temp && temp.length > 0) {
          // const res = temp[0];
          const deviceSerial = temp[1];
          const validateCode = temp[2];
          console.log(temp, deviceSerial, validateCode);
          wx.setStorage({
            key: "deviceSerial",
            data: deviceSerial,
          });

          wx.setStorage({
            key: "validateCode",
            data: validateCode,
          });
        }
      },
    });
  }

  searchDeviceInfo = (accessToken = "", deviceSerial = "") => {
    const promise = new Promise((resolve, reject) => {
      if (!accessToken || !deviceSerial) {
        reject("searchDeviceInfo:fail:params error");
      }
      wx.request({
        url: `https://open.ys7.com/api/v3/device/searchDeviceInfo`, 
        method: 'POST',
        data: { accessToken, deviceSerial },
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'accessToken': accessToken || ''
        },
        success: (res) => {
          console.log(res.data);
          
          if (res.data) {
            resolve(res.data);
          } else {
            wx.showToast({
              title: '网络异常请稍后重试',
              icon: 'error'
            })
            reject("searchDeviceInfo:fail:request fail");
          }
        },
        error:(err)=>{
          console.log(err);
          wx.showToast({
            title: '网络异常请稍后重试',
            icon: 'error'
          });
          reject("searchDeviceInfo:fail:network error")
        },
      })
    });

    return promise;
  };

  connectWifi = (deviceSerial = "", validateCode = "", accessToken = "", BSSID, SSID, wifiPassword) => {
    // TODO: 新增onStatusChange入参，在函数内任务变更时对外进行广播
    // TODO: 新增debugger入参，控制totast展示错误
    return new Promise(async (resolveGlobal, rejectGlobal) => {
      console.log("sdk里接收到的参数:", { deviceSerial, validateCode, accessToken, BSSID, SSID, wifiPassword });
      if (!accessToken || !deviceSerial || !validateCode || !BSSID || !SSID || !wifiPassword) {
        rejectGlobal("connectWifi:fail:params error");
      }
      
      const deviceSSID = "SoftAP_" + deviceSerial;
      const devicePassword = "SoftAP_" + validateCode;

      // 任务总时长是否超时
      const isTaskTimeout = (() => {
        const timeout = 90000 // 任务总超时时间
        const startTime = new Date().getTime()
        return () => new Date().getTime() - startTime > timeout
      })()
      // 设置超时promise
      const timeoutPromise = (time) => {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve('timeoutPromise')
          }, time)
        })
      }
      // 设备配置网络wifi
      const wifiConfig = (SSID, BSSID, wifiPassword, accessToken) => {
        return new Promise((resolve, reject) => {
          console.log("配网中：", { SSID, BSSID, wifiPassword, accessToken });
          wx.request({
            url: "http://192.168.8.1:8682/PreNetwork/WifiConfig",
            method: "PUT",
            timeout: 30000,
            data: {
              areaCode: "",
              token: accessToken,
              lbs_domain: "open.ys7.com",
              wifi_info: {
                bssid: BSSID,
                ssid: SSID,
                password: wifiPassword,
              },
              token: "",
            },
            header: {
              "content-type": "text/plain",
            },
            success: (res) => {
              if (res && res.data) {
                console.log("配网成功:", res);
                resolve(true)
              } else {
                console.log("配网失败：", res);
                resolve('retry');
              }
            },
            fail: (err) => {
              console.log("配网接口调用失败：:", err);
              resolve('retry');
            },
          });
        })
      }

      // 初始化wifi
      const taskInitWifi = async () => {
        const res = await wx.startWifi()
        console.log('微信wifi模块初始化：', res)
        // TODO: 获取当前连接wifi，是否SSID和入参一致，且频段符合要求，或者为设备wifi，则继续往后执行，否则提示浏览用户（也可作为外部前置逻辑去判断）
        return true
      }

      // 连接设备wifi
      const taskConnectDeviceWifi = async (options) => {
        console.log("开始连接设备：", options);
        try {
          const res = await wx.connectWifi(options)
          if (res.errCode === 0 || res.errMsg === "connectWifi:ok") {
            console.log("连接设备成功:", res);
            return true
          } else {
            Promise.reject(new Error(res))
          }
        } catch (error) {
          // 1、捕获 connectWifi api的报错情况 2、捕获errCode非0的情况
          console.log('连接设备失败：', error)
          // 弹窗显示
          const res = await wx.showModal({ title: '提示', confirmText: '手动连接', content: `设备连接失败，请手动找寻名称为${deviceSSID}的wifi进行连接，密码为：${devicePassword}` })
          if (res.cancel) {
            console.log('点击取消，终止连接设备')
            rejectGlobal('connectWifi:fail:connect cancel')
            return false
          }
          // 跳转wifi列表，进行手动连接
          return await taskConnectDeviceWifi({ ...options, maunal: true })
        }
      }

      // 设备连接网络
      const taskDeviceConnectNetwork = async(count) => {
        const loopCount = count || 1
        // 调用接口，增加10s的最小调用时间，兼容ios 调用wx.connectWifi返回连接成功，但页面延迟连接的情况
        const [res, timePromise] = await Promise.all([wifiConfig(SSID, BSSID, wifiPassword, accessToken), timeoutPromise(5000)])
        if (res === 'retry') {
          // 接口报错，重新发起请求
          if (isTaskTimeout() && loopCount > 3) {
            // 重试超出限制，reject指定报错
            console.log(`配网总时长已超时并且重试超过3次，退出配网`)
            rejectGlobal("connectWifi:fail:connect deviceNetwork fail")
            return false
          } else {
            // 重新进行设备连网
            return await taskDeviceConnectNetwork(loopCount + 1)
          }
        } else {
          // wifiConfig任务 胜出
          res && await new Promise((resolve) => {
          // 因为设备收到wifi信息后，到配网完成还需要一段时间,设置一个5s的等待时间
            setTimeout(() => resolve(), 5000)
          })
          return true
        }
      }


      // 初始化Wifi模块
      (await taskInitWifi()) &&
      // 连接设备Wifi
      (await taskConnectDeviceWifi({ SSID: deviceSSID, password: devicePassword })) &&
      // 设备连接网络Wifi
      (await taskDeviceConnectNetwork()) &&
      resolveGlobal()
    });
  };

  cancelConfigWifi = () => {
    if (wifiConfigTimer) {
      console.log("清除超时调用的timer:", wifiConfigTimer);
      clearTimeout(wifiConfigTimer);
    }
    if (wifiConnectTimer) {
      console.log("清除超时响应的timer:", wifiConnectTimer);

      clearTimeout(wifiConnectTimer);
    }
  };
  // check network
  checkNetWork = () => {
    wx.getNetworkType({
      success(res) {
        const networkType = res.networkType;
        if (!networkType || networkType === "none") {
          wx.showToast({
            title: "当前网络异常",
            icon: "none",
            duration: 2000,
          });
          return;
        }
      },
    });
  };
}

export const EConnectWifi = (props) => {
  const wechat_econnectWif_sdk = new WeChat_EConnectWifi(props);
  return wechat_econnectWif_sdk;
};
